package cn.actoncode.boot.module.ai.util;

import cn.actoncode.boot.module.ai.dal.redis.no.UniqueNoRedisDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * 唯一编号生成工具
 *
 * @author bin
 */
@Component
public class UniqueNoUtil {

    // AI写作业务编码
    public final static String AI_WRITE_CODE = "101";

    // AI对话业务编码
    public final static String AI_TALK_CODE = "102";

    private static UniqueNoRedisDAO uniqueNoRedisDAO;

    @Autowired
    public UniqueNoUtil(UniqueNoRedisDAO uniqueNoRedisDAO) {
        UniqueNoUtil.uniqueNoRedisDAO = uniqueNoRedisDAO;
    }

    /**
     * 生成AI写作唯一编号
     */
    public static Long getWriteUniqueNo(LocalDateTime date) {

        return Long.valueOf(getUniqueNo(AI_WRITE_CODE, date));
    }

    /**
     * 生成AI对话唯一编号
     */
    public static Long getTalkUniqueNo(LocalDateTime date) {

        return Long.valueOf(getUniqueNo(AI_TALK_CODE, date));
    }

    /**
     * 生成唯一编号
     */
    private static String getUniqueNo(String code, LocalDateTime date) {

        //获取当前年月日
        String ymd = getYMD(date);
        //获取用户当天的incr值
        Long incr = uniqueNoRedisDAO.incr(ymd);

        //拼接订单号：业务编码3位 + 年2位 + 月2位 + 日2位 + incr码
        return code + ymd + incr;
    }

    /**
     * 获取日期的年月日
     */
    private static String getYMD(LocalDateTime date){

        int year = date.getYear() - 2000;
        int month = date.getMonthValue();
        int day = date.getDayOfMonth();

        String monthStr = month > 9 ? month + "" : "0" + month;
        String dayStr = day > 9 ? day + "" : "0" + day;
        return year + monthStr + dayStr;
    }

    /**
     * 获取日期的年月日时分秒毫秒
     */
    private static String getYMDHMSMILL(Date date){

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        int year = calendar.get(Calendar.YEAR) - 2000;
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        int millisecond = calendar.get(Calendar.MILLISECOND);

        String monthStr = month > 9 ? month + "" : "0" + month;
        String dayStr = day > 9 ? day + "" : "0" + day;
        return year + monthStr + dayStr + hour + minute + second + millisecond;
    }

}
